package list;

/**
 * @ClassName: LinkLiist
 * @Author: wangyusong
 * @Date: 2020-10-08 20:17
 * @Desciprion: 单链表结构及基础操作
 * @Version:
 */
public class LinkLiistNode<T> {
    /**单链表结构*/
    private class LNode{
        private T data;
        private LNode next;

        public LNode(T data, LNode next) {
            this.data = data;
            this.next = next;
        }

        public LNode(T data) {
            this(data,null);
        }

        public T getData() {
            return data;
        }

        public void setData(T data) {
            this.data = data;
        }

        public LNode getNext() {
            return next;
        }

        public void setNext(LNode next) {
            this.next = next;
        }
    }
    /**头指针*/
    private LNode head;
    private int  size;

    public LinkLiistNode() {
        this.head = null;
        this.size = 0;
    }

    public LNode getHead() {
        return head;
    }

    public void setHead(LNode head) {
        this.head = head;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    /**使用头插法建立单链表*/
    public void addFrist(T data){
        LNode node = new LNode(data);
        node.next = this.head;
        this.head = node;
        this.size++;

    }

    /**尾插法*/
    public  void addLast(T data){
        this.add(data,this.size);
    }

    /**向链表中间插入元素*/
    public void add(T data,int index){
        /*越界异常*/
        if (index < 0 || index > size){
            throw new IllegalArgumentException("index is error");
        }
        /*头部插入*/
        if (index == 0){
            this.addFrist(data);
        }
        /*找到需要插入节点的一个节点*/
        LNode preNode = this.head;
        for (int i = 0; i < index-1;i++){
            preNode = preNode.next;
        }

        LNode node =new LNode(data);
        /*新节点链上上一个节点的指向*/
        node.next = preNode.next;
        preNode.next = node;
        this.size++;
    }

    /**删除链表元素*/
    public void remove(T data){
        if (head == null){
            System.out.println("无元素可删除");
        }

    //要删除的元素与头节点的元素相同
    while (head != null && head.data.equals(data)){
        head = head.next;
        this.size--;
    }

        LNode cur = this.head;
        while (cur.next != null){
            if (cur.next.data.equals(data)){
                cur.next = cur.next.next;
                this.size--;
            }else {
                cur = cur.next;
            }
        }
    }
}
